package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    public RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams requestParams) {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        //复杂查询
        bool(requestParams,source);
        //设置分页
        source.from((requestParams.getPage() - 1) * requestParams.getPage()).size(requestParams.getSize());
        //距离查询
        if(StringUtils.isNotBlank(requestParams.getLocation())){
            source.sort(SortBuilders.geoDistanceSort("location",new GeoPoint(requestParams.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }
        //响应请求
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            PageResult pageResult = handleResponse(response);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 聚合
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        bool(requestParams,source);
        source.size(0);
        //封装分组
        aggregation(source);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            Map<String,List<String>> map = new HashMap<>();
           //封装返回数据
            List<String> brandAgg = getAggName(aggregations, "brandAgg");
            map.put("brand",brandAgg);
            List<String> cityAgg = getAggName(aggregations, "cityAgg");
            map.put("city",cityAgg);
            List<String> starNameAgg = getAggName(aggregations, "starNameAgg");
            map.put("starName",starNameAgg);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException();
        }
    }

    /**
     *
     * 拼音搜索自动补全
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.suggest(new SuggestBuilder()
                .addSuggestion("suggestions",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(prefix)
                                .skipDuplicates(true)
                                .size(10)));
        try {
            //请求相应
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //根据补全查询名称，获取补全结果
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 根据id删除数据
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加数据
     * @param id
     */
    @Override
    public void insertById(Long id) {
        if("".equals(id)||id==null){
            throw new RuntimeException("id不能为空");
        }
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = getById(id);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 相应分组
     * @param aggregations
     * @param name
     * @return
     */
    public List<String> getAggName(Aggregations aggregations,String name){
         Terms terms = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }

    /**
     * 封装分组查询
     * @param source
     */
    public void aggregation(SearchSourceBuilder source){
        source.aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(5)
        );
        source.aggregation(
                AggregationBuilders.terms("cityAgg").field("city").size(10)
        );
        source.aggregation(
                AggregationBuilders.terms("starNameAgg").field("starName").size(5)
        );
    }

    /**
     * 布尔查询
     * @param requestParams
     * @param source
     * @return
     */
    public void bool(RequestParams requestParams, SearchSourceBuilder source) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //判断requestParams.getKey()是否为空
        if (StringUtils.isNotBlank(requestParams.getKey())) {
            //不为空按照条件查询
            MatchQueryBuilder name = QueryBuilders.matchQuery("all", requestParams.getKey());
            boolQueryBuilder.must(name);
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name").requireFieldMatch(false);
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            source.highlighter(highlightBuilder);
        } else {
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            boolQueryBuilder.must(matchAllQueryBuilder);
        }
        //判断sortBy的参数是什么1.default 2.score 3.price
        if(requestParams.getSortBy().equals("score")){
            source.sort("score", SortOrder.DESC);
        }else if(requestParams.getSortBy().equals("price")){
            source.sort("price",SortOrder.ASC);
        }
        //城市过滤查询
        if (StringUtils.isNotBlank(requestParams.getCity())) {
            TermQueryBuilder city = QueryBuilders.termQuery("city", requestParams.getCity());
            boolQueryBuilder.filter(city);
        }
        if (StringUtils.isNotBlank(requestParams.getBrand())) {
            //品牌过滤
            TermQueryBuilder brand = QueryBuilders.termQuery("brand", requestParams.getBrand());
            boolQueryBuilder.filter(brand);
        }
        if (requestParams.getMaxPrice() != null && requestParams.getMinPrice() != null) {
            //价格过滤
            RangeQueryBuilder price = QueryBuilders.rangeQuery("price").gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice());
            boolQueryBuilder.filter(price);
        }
        if (StringUtils.isNotBlank(requestParams.getStarName())) {
            //星级过滤
            TermQueryBuilder starname = QueryBuilders.termQuery("starName", requestParams.getStarName());
            boolQueryBuilder.filter(starname);
        }
        //算分查询
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        }).boostMode(CombineFunction.SUM);
        source.query(functionScoreQuery);
    }

    /**
     * 解析响应结果
     *
     * @param response
     * @return
     */
    public PageResult handleResponse(SearchResponse response) {
        Long total = response.getHits().getTotalHits().value;
        //查询条数
        PageResult pageResult = new PageResult();
        //创建List集合
        List<HotelDoc> list = new ArrayList<>();
        //存入pageResult
        pageResult.setTotal(total);
        for (SearchHit hit : response.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //根据字段名获得高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField!=null){
                    hotelDoc.setName(highlightField.getFragments()[0].string());
                }
            }
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length>0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            //将数据存入集合中
            list.add(hotelDoc);
        }
        //将集合存入pageResult
        pageResult.setHotels(list);
        return pageResult;
    }
}
